import 'dart:core';

import 'package:flutter/material.dart';

class CustomStarView extends StatefulWidget {
  final double rating;
  final double maxRating;
  //
  final int maxCount;
  final double size;
  //进度条色值
  final Color unSelectColor;
  final Color selectColor;
  //自定义图片
  final Widget unSelectImage;
  final Widget selectImage;

  CustomStarView({
    required this.rating,
    this.maxRating = 10,
    this.maxCount = 5,
    this.size = 30,
    this.unSelectColor = Colors.grey,
    this.selectColor = Colors.red,
    Widget? unselectImage,
    Widget? selectImage,
  })  : unSelectImage = unselectImage ?? Icon(Icons.star_border, color: unSelectColor, size: size),
        selectImage = selectImage ?? Icon(Icons.star, color: selectColor, size: size);

  @override
  State<CustomStarView> createState() => _CustomStarViewState();
}

class _CustomStarViewState extends State<CustomStarView> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Row(mainAxisSize: MainAxisSize.min, children: buildUnselectStar()),
        Row(mainAxisSize: MainAxisSize.min, children: buildselectStar())
      ],
    );
  }

  List<Widget> buildUnselectStar() {
    return List.generate(widget.maxCount, (index) {
      return widget.unSelectImage;
    });
  }

  List<Widget> buildselectStar() {
    List<Widget> stars = [];
    final selectStar = widget.selectImage;
    double oneStarValue = widget.maxRating / widget.maxCount;
    //满星添加
    int entirCount = (widget.rating / oneStarValue).floor();
    for (int i = 0; i < entirCount; i++) {
      stars.add(selectStar);
    }
    //裁剪星添加
    double leftSize = ((widget.rating / oneStarValue) - entirCount) * widget.size;
    final halfStar = ClipRect(
      clipper: SelfCliper(leftSize),
      child: selectStar,
    );
    stars.add(halfStar);


    if(stars.length>widget.maxCount){
      return stars.sublist(0,widget.maxCount);
    }
    return stars;
  }
}

class SelfCliper extends CustomClipper<Rect> {
  double widget;

  SelfCliper(this.widget);

  @override
  Rect getClip(Size size) {
    return Rect.fromLTRB(0, 0, widget, size.height);
  }

  @override
  bool shouldReclip(SelfCliper oldClipper) {
    return oldClipper.widget != widget;
  }
}
